#include "libstate.h"

int set_states(char *id, char *stateXml) {
	struct soap *soap = soap_new();
	char * message;

	char * state_store_location;
	config_get_string(&state_store_location, "STATE_STORE_LOCATION");

	if (soap_call_ns__store(soap, state_store_location, NULL, id, stateXml,
			&message) != SOAP_OK)
		soap_print_fault(soap, stderr);
	else
		fprintf(stderr, "[soap] %s\n", message);

	soap_destroy(soap);
	soap_end(soap);
	soap_done(soap);
	return 0;
}

int get_states(char *id, char **stateXml) {
	*stateXml = NULL;
	struct soap *soap = soap_new();
	char * result;

	char * state_store_location;
	config_get_string(&state_store_location, "STATE_STORE_LOCATION");

	if (soap_call_ns__getState(soap, state_store_location, NULL, id, &result)
			!= SOAP_OK) {
		soap_print_fault(soap, stderr);

	} else {
		if (result) {
			*stateXml = (char *) malloc(1024);
			strcpy(*stateXml, result);
		}
	}
	soap_destroy(soap);
	soap_end(soap);
	soap_done(soap);
	return 0;
}

int state_get_string(char ** variable, const char * name, char *statesXml) {
	xmlDoc * doc = NULL;
	xmlNode *root = NULL;
	xmlNode *states = NULL;
	xmlNode *state = NULL;
	*variable = NULL;

	doc = xmlReadDoc(statesXml, NULL, NULL, XML_PARSE_NOWARNING);
	root = xmlDocGetRootElement(doc);
	states = root ->children;
	if (states) {
		state = states->children;
		while (state) {
			if (xmlStrEqual(xmlGetProp(state, "name"), name)) {
				*variable = malloc(256);
				strcpy(*variable, xmlNodeListGetString(doc, state->children, 1));
				break;
			}
			state = state->next;
		}
	}
	xmlFreeDoc(doc);
	return 0;
}
